package cn.zou.mvc;

import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;

public class PramasNameUtils {
	//获取方法参数
	public String[] getPramasName(Class  clazz,Class[] prams) throws NotFoundException{
		  ClassPool pool = ClassPool.getDefault();  
		  ClassClassPath classPath = new ClassClassPath(this.getClass());  
		  pool.insertClassPath(classPath);
	      CtClass cc = pool.get(clazz.getName());
	        CtClass[] Cts=new CtClass[prams.length];
	        for(int i=0;i<prams.length;i++)Cts[i]=pool.get(prams[i].getName());
	        CtMethod cm = cc.getDeclaredMethod("test",Cts);  
	        // 使用javaassist的反射方法获取方法的参数名  
	        MethodInfo methodInfo = cm.getMethodInfo();  
	        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();  
	        LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);  
	        if (attr == null) {  
	            // exception  
	        	throw new NotFoundException("没有找到 参数名");
	        }  
	        String[] paramNames = new String[cm.getParameterTypes().length];  
	        int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;  
	        for (int i = 0; i < paramNames.length; i++)  
	            paramNames[i] = attr.variableName(i + pos);      
		return paramNames;
	}
}
